/**
 * @author Syed Irfan (A0092662)
 */
package sg.edu.nus.iss.team4ft.ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JSeparator;

import sg.edu.nus.iss.team4ft.exception.BillingException;
import sg.edu.nus.iss.team4ft.exception.InvalidBillInputException;
import sg.edu.nus.iss.team4ft.manager.BillManager;
import sg.edu.nus.iss.team4ft.manager.CustomerAccountManager;
import sg.edu.nus.iss.team4ft.service.Bill;
import sg.edu.nus.iss.team4ft.service.CustomerAccount;
import sg.edu.nus.iss.team4ft.util.AppConstant;
import sg.edu.nus.iss.team4ft.util.DateUtil;
import sg.edu.nus.iss.team4ft.util.Item;

import com.cloudgarden.layout.AnchorConstraint;
import com.cloudgarden.layout.AnchorLayout;

/**
 * This code was edited or generated using CloudGarden's Jigloo SWT/Swing GUI
 * Builder, which is free for non-commercial use. If Jigloo is being used
 * commercially (ie, by a corporation, company or business for any purpose
 * whatever) then you should purchase a license for each developer using Jigloo.
 * Please visit www.cloudgarden.com for details. Use of Jigloo implies
 * acceptance of these licensing terms. A COMMERCIAL LICENSE HAS NOT BEEN
 * PURCHASED FOR THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED LEGALLY FOR
 * ANY CORPORATE OR COMMERCIAL PURPOSE.
 * 
 * 
 */

public class BillingPanel extends javax.swing.JPanel {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JButton jButtonViewBill;
	private JSeparator jSeparator1;
	private JComboBox jMonth;
	private JComboBox jcmbobxYear;
	private JComboBox jcmbobxMonth;
	private JLabel lblYear;
	private JLabel lblMonth;
	private JComboBox jComboBoxSelectYear;
	private JLabel jLabelYear;
	private JLabel jLabelAccountNum;
	private JLabel jLabelMonth;
	private JButton jButtonGetAllMonths;
	private BillManager billManager;
	private JComboBox jComboBoxCustAccList;
	private ComboBoxModel jComboBoxCustAccListModel;

	public BillingPanel() {
		super();
		billManager = new BillManager();
		initGUI();
	}

	public void initGUI() {
		try {
			AnchorLayout thisLayout = new AnchorLayout();
			this.setLayout(thisLayout);
			this.setPreferredSize(new java.awt.Dimension(484, 322));
			{
				jComboBoxCustAccListModel = 
						new DefaultComboBoxModel(getAllCustAccNum());
				jComboBoxCustAccList = new JComboBox();
				this.add(jComboBoxCustAccList, new AnchorConstraint(60, 958, 131, 634, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
				jComboBoxCustAccList.setModel(jComboBoxCustAccListModel);
				jComboBoxCustAccList.setPreferredSize(new java.awt.Dimension(146, 23));
			}
			{
				jSeparator1 = new JSeparator();
				this.add(jSeparator1, new AnchorConstraint(436, 1001, 467, 1, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
				jSeparator1.setPreferredSize(new java.awt.Dimension(400, 10));
			}
			{
				Item[] items = getItem(DateUtil.getDate());

				ComboBoxModel jcmbobxMonthModel = 
						new DefaultComboBoxModel(items);
				jcmbobxMonth = new JComboBox();
				this.add(jcmbobxMonth, new AnchorConstraint(541, 763, 613, 635, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
				jcmbobxMonth.setModel(jcmbobxMonthModel);
				jcmbobxMonth.setPreferredSize(new java.awt.Dimension(62, 23));
			}
			{
				lblYear = new JLabel();
				this.add(lblYear, new AnchorConstraint(718, 600, 768, 443, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
				lblYear.setText("Select Year :");
				lblYear.setPreferredSize(new java.awt.Dimension(76, 16));
			}
			{
				lblMonth = new JLabel();
				this.add(lblMonth, new AnchorConstraint(557, 635, 607, 443, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
				lblMonth.setText("Select Month :");
				lblMonth.setPreferredSize(new java.awt.Dimension(93, 16));
			}
			{
				jButtonViewBill = new JButton();
				jButtonViewBill.setText("View Customer Bill");
				jButtonViewBill.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						try {
							jButtonViewBillActionPerformed(evt);
						} catch (BillingException e) {
							showErrorDialog(AppConstant.BILL_ERR_ACC_NOT_FOUND);
							e.printStackTrace();
						} catch (InvalidBillInputException e){
							showErrorDialog(AppConstant.BILL_ERR_ACC_NUM);
							e.printStackTrace();
						} catch (Exception e) {
							showErrorDialog(AppConstant.ERR_MSG);
							e.printStackTrace();
						}
					}

					
				});
			}
			{
				jLabelMonth = new JLabel();
				jLabelMonth.setText("Select Month :");
			}
			{
				jLabelYear = new JLabel();
				jLabelYear.setText("Select Year :");
			}
			{
				ComboBoxModel jComboBoxSelectYearModel = new DefaultComboBoxModel(DateUtil.YEAR_SELECT);
				jComboBoxSelectYear = new JComboBox();
				this.add(jComboBoxSelectYear, new AnchorConstraint(299, 763, 371, 635, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
				this.add(jLabelYear, new AnchorConstraint(327, 635, 377, 443, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
				this.add(jLabelMonth, new AnchorConstraint(190, 660, 240, 443, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
				jLabelMonth.setPreferredSize(new java.awt.Dimension(105, 16));
				jLabelYear.setPreferredSize(new java.awt.Dimension(93, 16));
				jComboBoxSelectYear.setModel(jComboBoxSelectYearModel);
				jComboBoxSelectYear.setPreferredSize(new java.awt.Dimension(62, 23));
				jComboBoxSelectYear.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						jComboBoxSelectYearActionPerformed(evt);
					}
				});
			}
			{
				jLabelAccountNum = new JLabel();
				jLabelAccountNum.setText("Account No :");
			}
			{
				Item[] items = getItem(DateUtil.getDate());

				ComboBoxModel jMonthModel = new DefaultComboBoxModel(items);
				jMonth = new JComboBox();
				this.add(jMonth, new AnchorConstraint(172, 763, 234, 635, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
				this.add(jLabelAccountNum, new AnchorConstraint(69, 635, 119, 443, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
				this.add(jButtonViewBill, new AnchorConstraint(60, 375, 131, 32, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
				jButtonViewBill.setPreferredSize(new java.awt.Dimension(166, 23));
				jLabelAccountNum.setPreferredSize(new java.awt.Dimension(93, 16));
				jMonth.setModel(jMonthModel);
				jMonth.setPreferredSize(new java.awt.Dimension(62, 20));

			}
			{
				jButtonGetAllMonths = new JButton();
				this.add(jButtonGetAllMonths, new AnchorConstraint(548, 375, 619, 32, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
				jButtonGetAllMonths.setText("Generate Monthly Bill");
				jButtonGetAllMonths.setPreferredSize(new java.awt.Dimension(166, 23));
				jButtonGetAllMonths.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						try {
							jButtonGetAllMonthsActionPerformed(evt);
						} catch (BillingException e) {
							showErrorDialog(AppConstant.BILL_ERR_BILL_GEN);
							e.printStackTrace();
						}
					}
				});
			}
			{
				ComboBoxModel jComboBox1Model = 
						new DefaultComboBoxModel(DateUtil.YEAR_SELECT);
				jcmbobxYear = new JComboBox();
				this.add(jcmbobxYear, new AnchorConstraint(703, 763, 774, 635, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
				jcmbobxYear.setModel(jComboBox1Model);
				jcmbobxYear.setPreferredSize(new java.awt.Dimension(62, 23));
				jcmbobxYear.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						jcmbobxYearActionPerformed(evt);
					}
				});
			}
			
			if((AppConstant.USER.getRole()).equals(AppConstant.AGENT)){
				jcmbobxYear.setVisible(false);
				jButtonGetAllMonths.setVisible(false);
				jcmbobxMonth.setVisible(false);
				lblMonth.setVisible(false);
				lblYear.setVisible(false);				
			}
			
			this.setSize(450, 322);
		} catch (Exception e) {
			showErrorDialog(AppConstant.ERR_MSG);
			e.printStackTrace();
		}
	}
	
	private void showErrorDialog(String errorMsg) {
		JOptionPane.showMessageDialog(null,
				errorMsg,
			    "Error",
			    JOptionPane.ERROR_MESSAGE);

	}
	
	/**
	 * 
	 * @param evt
	 * @throws BillingException
	 */
	private void jButtonGetAllMonthsActionPerformed(ActionEvent evt)
			throws BillingException {
		System.out.println("jButtonGetAllMonths.actionPerformed, event=" + evt);
		Item month = (Item) jcmbobxMonth.getSelectedItem();
		String year = jcmbobxYear.getSelectedItem().toString();
		String date = month.getDescription()+" "+year;
		
		try {
			jComboBoxCustAccListModel = 
					new DefaultComboBoxModel(getAllCustAccNum());
			jComboBoxCustAccList.setModel(jComboBoxCustAccListModel);
		} catch (Exception e) {	
			e.printStackTrace();
			throw new BillingException();
		}
		
		int option = 1;
		//check if file exists: for displaying appropriate confirm dialog.
		if(billManager.billFileExist(month.getId(), Integer.parseInt(year))){
			option = JOptionPane.showConfirmDialog(null, String.format(AppConstant.CONFIRM_FILE_EXIST, date),AppConstant.CONFIRM_TITLE,JOptionPane.YES_NO_CANCEL_OPTION);
		}else{
			option = JOptionPane.showConfirmDialog(null, AppConstant.CONFIRM_PROCEED,AppConstant.CONFIRM_TITLE,JOptionPane.YES_NO_CANCEL_OPTION);	
		}
		
		if (option==0){
			System.out.println("<BillingPanel> Month: "+month.getDescription()+" Year: "+year);
			billManager.genMonthlyBill(month.getId(), Integer.parseInt(year));
			JOptionPane.showMessageDialog(null,"File Generated for Month:["+month.getDescription()+"] in Year:["+year+"]","File Generated",JOptionPane.INFORMATION_MESSAGE);
		}else			
			System.out.println("jOptionPane2 has No Action");	
	}
	
	public JComboBox getJMonth() {
		return jMonth;
	}

	private void jButtonViewBillActionPerformed(ActionEvent evt) throws BillingException, InvalidBillInputException, IOException, ClassNotFoundException, ParseException, CloneNotSupportedException {
		System.out.println("jButtonViewBill.actionPerformed, event=" + evt);
		String acct = jComboBoxCustAccList.getSelectedItem().toString();
		Item month = (Item) jMonth.getSelectedItem();
		int year = Integer.parseInt(jComboBoxSelectYear.getSelectedItem().toString());
		
		System.out.println("<BillingPanel> Acct: " + acct + " Month: "+ month.toString() + " Year: " + year);
		
		Bill bill = billManager.getBill(acct,month.getId(),year);
		BillReportJFrame billReport = new BillReportJFrame(bill);
		billReport.setLocationRelativeTo(null);
		billReport.setVisible(true);
	}
	
	private Object[] getAllCustAccNum() throws Exception{
		CustomerAccountManager cam = new CustomerAccountManager();
		ArrayList<CustomerAccount> custList = cam.getAllCustomerAccount();
		ArrayList<String> custAccNumList = new ArrayList<String>();
		for(CustomerAccount custAcc: custList){
			custAccNumList.add(custAcc.getAccount().getAccountNumber());
		}
		
		Object[] custArray = custAccNumList.toArray();
		
		return custArray;
	}
	
	private void jComboBoxSelectYearActionPerformed(ActionEvent evt) {
		System.out.println("jComboBoxSelectYear.actionPerformed, event="+evt);
		int year = Integer.parseInt(jComboBoxSelectYear.getSelectedItem().toString());
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, year);		
		Item[] items = getItem(cal.getTime());
		ComboBoxModel jMonthModel = new DefaultComboBoxModel(items);
		jMonth.setModel(jMonthModel);
	}
	
	private void jcmbobxYearActionPerformed(ActionEvent evt) {
		System.out.println("jcmbobxYear.actionPerformed, event="+evt);
		int year = Integer.parseInt(jcmbobxYear.getSelectedItem().toString());
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, year);		
		Item[] items = getItem(cal.getTime());
		ComboBoxModel jcmbobxMonthModel = new DefaultComboBoxModel(items);
		jcmbobxMonth.setModel(jcmbobxMonthModel);
	}
	
	private Item[] getItem(Date date){
		Item[] items = DateUtil.MONTHS_VALUE;				
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		Calendar calCurr = Calendar.getInstance();
		calCurr.setTime(DateUtil.getDate());
		if(cal.get(Calendar.YEAR)>=calCurr.get(Calendar.YEAR)){
			List<Item> month = new ArrayList<Item>();
			for(int count=0;count<=cal.MONTH;count++){
				month.add(items[count]);
			}
			items = (Item[]) month.toArray(new Item[0]);
		}
		System.out.println("Month List:");
		for(Item item:items){
			System.out.println("Month Added: "+item.getDescription());
		}
		return items;
	}
}